package com.bfly.mall.admin.service.impl;

import com.bfly.core.base.service.BaseServiceImpl;
import com.bfly.mall.admin.dao.RoleMapper;
import com.bfly.mall.admin.entity.Role;
import com.bfly.mall.admin.dto.RoleDTO;
import com.bfly.mall.admin.service.IRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 *
 * @author 长沙商脉科技有限公司
 * @date 2020/10/16 12:05
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role, Integer> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(RoleDTO roleDTO) {
        Role role = new Role();
        role.setCreateDate(new Date());
        role.setUpdateDate(role.getCreateDate());
        BeanUtils.copyProperties(roleDTO, role);
        role.setSys(false);
        super.save(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(RoleDTO roleDTO) {
        Role role = super.get(roleDTO.getId());
        role.setSys(false);
        role.setName(roleDTO.getName());
        role.setRemark(roleDTO.getRemark());
        role.setUpdateDate(new Date());
        super.edit(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int remove(Integer... roleIds) {
        for (Integer roleId : roleIds) {
            // 删除角色先回收用户角色和回收角色权限
            roleMapper.clearRoleAdminShip(roleId);
            roleMapper.clearRoleMenuShip(roleId);
        }
        return super.remove(roleIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindRoleAndMenu(int roleId, Integer... menuIds) {
        // 先清空角色和菜单的绑定关系 然后添加
        roleMapper.clearRoleMenuShip(roleId);
        for (Integer menuId : menuIds) {
            roleMapper.bindRoleMenuShip(roleId,menuId);
        }
    }
}
